//  Algemen functies
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <regex.h>
#include "alg.h"

//vertaal char naar char
void chartochar(char *woord, char van, char naar)
{
	int tel;
	for (tel = 0; woord[tel] != '\0'; tel++) {
		if (woord[tel] == van)
			woord[tel] = naar;
	}
}

// html characters vertalen, zoals &amp;
void conv_htmlchar(char *convert)
{
	char *buffer;
	int tel;
	int tel2 = 0;

	size_t groot = (strlen(convert) + 1) * sizeof(char);

	buffer = (char *) malloc(groot);
	for (tel = 0; convert[tel] != '\0'; tel++) {
		if (convert[tel] == '&'
		    && !strncmp(&convert[tel], "&amp;", 5)) {
			buffer[tel2] = '&';
			tel += 4;
			tel2++;
		} else {
			buffer[tel2] = convert[tel];
			tel2++;
		}
	}
	buffer[tel2] = '\0';
	strcpy(convert, buffer);
	free(buffer);
}

//converteren & naar html &amp;
//converteren &eacute; naar iso;
//\r wissen
//tags wissen
int conv_char(char *convert)
{
	int tel, tel2 = 0;
	int tag = 0;
	char buffer[4096];
	//return(1);
	for (tel = 0; convert[tel] != '\0'; tel++) {
		if (tag) {
			if (convert[tel] == '>')
				tag = 0;
			else
				continue;
		} else if (convert[tel] == '&') {
			if (!strncmp(&convert[tel], "&amp;", 5)) {
				buffer[tel2] = convert[tel];
				tel2++;
				continue;
			} else if (!strncmp(&convert[tel], "&nbsp;", 6)) {
				buffer[tel2] = ' ';
				tel2++;
				tel += 5;
			} else if (!strncmp(&convert[tel], "&quot;", 6)) {
				buffer[tel2] = 34;
				tel2++;
				tel += 5;
			} else if (!strncmp(&convert[tel], "&ldquo;", 7)) {
				buffer[tel2] = 34;
				tel2++;
				tel += 6;
			} else if (!strncmp(&convert[tel], "&rdquo;", 7)) {
				buffer[tel2] = 34;
				tel2++;
				tel += 6;
			} else if (!strncmp(&convert[tel], "&lsquo;", 7)) {
				buffer[tel2] = 96;
				tel2++;
				tel += 6;
			} else if (!strncmp(&convert[tel], "&rsquo;", 7)) {
				buffer[tel2] = 44;
				tel2++;
				tel += 6;
			} else if (!strncmp(&convert[tel], "&ldquot;", 8)) {
				buffer[tel2] = 34;
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&rdquot;", 8)) {
				buffer[tel2] = 34;
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&lsquot;", 8)) {
				buffer[tel2] = 96;
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&rsquot;", 8)) {
				buffer[tel2] = 44;
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&aacute;", 8)) {
				buffer[tel2] = 225;
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&oacute;", 8)) {
				buffer[tel2] = 243;
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&eacute;", 8)) {
				buffer[tel2] = 233;
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&egrave;", 8)) {
				buffer[tel2] = 232;
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&hellip;", 8)) {
				buffer[tel2] = '.';
				tel2++;
				buffer[tel2] = '.';
				tel2++;
				buffer[tel2] = '.';
				tel2++;
				tel += 7;
			} else if (!strncmp(&convert[tel], "&#039;", 6)) {
				buffer[tel2] = 39;
				tel2++;
				tel += 5;
			} else if (!strncmp(&convert[tel], "&uuml;", 6)) {
				buffer[tel2] = 253;
				tel2++;
				tel += 5;
			} else if (!strncmp(&convert[tel], "&ouml;", 6)) {
				buffer[tel2] = 246;
				tel2++;
				tel += 5;
			} else if (!strncmp(&convert[tel], "&iuml;", 6)) {
				buffer[tel2] = 239;
				tel2++;
				tel += 5;
			} else if (!strncmp(&convert[tel], "&euml;", 6)) {
				buffer[tel2] = 235;
				tel2++;
				tel += 5;
			} else {
				buffer[tel2] = '&';
				tel2++;
				buffer[tel2] = 'a';
				tel2++;
				buffer[tel2] = 'm';
				tel2++;
				buffer[tel2] = 'p';
				tel2++;
				buffer[tel2] = ';';
				tel2++;
			}
		} else if (convert[tel] == '\r')
			continue;
		else if (convert[tel] == '<')
			tag = 1;
		else {
			buffer[tel2] = convert[tel];
			tel2++;
		}
	}
	buffer[tel2] = '\0';
	strcpy(convert, buffer);
	return (1);
}

// channels vergelijken , 0 = niet gelijk
short compare_channels(channel * kanaal1, channel * kanaal2)
{
	short ret = 0, tel, tel2;
	char *buffer1, *buffer2;
	buffer1 = strdup(kanaal1->omschrijving);
	buffer2 = strdup(kanaal2->omschrijving);
	// spaties strippen
	tel2 = 0;
	for (tel = 0; kanaal1->omschrijving[tel] != '\0'; tel++) {
		if (kanaal1->omschrijving[tel] == ' ')
			continue;
		buffer1[tel2] = kanaal1->omschrijving[tel];
		tel2++;
	}
	buffer1[tel2] = '\0';

	tel2 = 0;
	for (tel = 0; kanaal2->omschrijving[tel] != '\0'; tel++) {
		if (kanaal2->omschrijving[tel] == ' ')
			continue;
		buffer2[tel2] = kanaal2->omschrijving[tel];
		tel2++;
	}
	buffer2[tel2] = '\0';

	if (!strcasecmp(buffer1, buffer2))
		ret = 1;
	free(buffer1);
	free(buffer2);
	return (ret);
}

//maken van nieuwe datum van bijv 40 oktober -> 9 november:
time_t makedate(int jaar, int maand, int dag, int uur, int min,
		char *convert, short tzone, time_t timet)
{
	extern short tz;
	struct tm *tijd;
	time_t tijdt;
	time_t ret;
	if (timet <= 0) {
		time(&tijdt);
		tijd = localtime(&tijdt);
		tijd->tm_year = jaar - 1900;
		tijd->tm_mon = maand - 1;
		tijd->tm_mday = dag;
		tijd->tm_hour = uur;
		tijd->tm_min = min;
		ret = mktime(tijd);
	} else {
		tijd = localtime(&timet);
		ret = mktime(tijd);
	}

	if (timet == 0)
		strftime(convert, 9, "%Y%m%d", tijd);
	else
		strftime(convert, 15, "%Y%m%d%H%M00", tijd);
/*
	if (tijd->tm_isdst > 0)
		tzone = 2;
	else
		tzone = 1;
*/
	tzone = tz;
	return (ret);
}

//converteren genre, return(0) als genre ongewijzigd
// genres staan in mythtv/themes/default/categories.xml
short convert_genre(char *genre)
{
	int tel;
	char *genres[] = {
		"Talk",		//0
		//"Animated",   //1
		"Animatie",	//1
		//"Comedy",     //2
		"Comedy",	//2
		//"Documentary",        //3
		"Documentaire",	//3
		//"Educational",        //4
		"Informatief",	//4
		//"Adult",      //5
		"Erotiek",	//5
		//"Movies",     //6
		"Film",		//6
		//"Music",      //7
		"Muziek",	//7
		//"Children",   //8
		"Jeugd",	//8
		//"Arts/Culture",       //9
		"Kunst/cultuur",	//9
		"Science/Nature",	//10
		//"News",               //11
		"Nieuws/actualiteiten",	//11
		"Drama",	//12
		//"Religion",   //13
		"Religieus",	//13
		"Sports",	//14
		"Science/Nature",	//15
		"Shopping",	//16
		"Cooking",	//17
		"Animals",	//18
		"SciFi",	//19
		"Sitcom",	//20
		"Health",	//21
		"Reality",	//22
		"Amusement",	//23
		"Overige",	//24
		"Serie/soap",	//25
		"Romance",	//26
		NULL
	};

	if (genre[0] == '\0' || genre == NULL) {
		strcpy(genre, "Unknown");
		return (0);
	}
	//Als ik bekend genre heb, niets doen
	for (tel = 0; genres[tel] != NULL; tel++) {
		if (!strcmp(genres[tel], genre))
			return (0);
	}
	if (!strncasecmp(genre, "edu", 3))
		strcpy(genre, genres[4]);
	else if (strcasestr(genre, "Document"))
		strcpy(genre, genres[3]);
	else if (!strncasecmp(genre, "com", 3))
		strcpy(genre, genres[2]);
	else if (!strncasecmp(genre, "ani", 3))
		strcpy(genre, genres[1]);
	else if (strcasestr(genre, "cartoon"))
		strcpy(genre, genres[1]);
	else if (!strncasecmp(genre, "overig", 6))
		strcpy(genre, genres[24]);
	else if (!strncasecmp(genre, "amu", 3))
		strcpy(genre, genres[23]);
	else if (strcasestr(genre, "entertainment"))
		strcpy(genre, genres[23]);
	else if (!strncasecmp(genre, "inf", 3))
		strcpy(genre, genres[4]);
	else if (!strncasecmp(genre, "kom", 3))
		strcpy(genre, genres[2]);
	else if (!strncasecmp(genre, "kun", 3))
		strcpy(genre, genres[9]);
	else if (!strncasecmp(genre, "mod", 3))
		strcpy(genre, genres[9]);
	else if (!strncasecmp(genre, "lif", 3))
		strcpy(genre, genres[0]);
	else if (strcasestr(genre, "nieuws"))
		strcpy(genre, genres[11]);
	else if (strcasestr(genre, "actualiteit"))
		strcpy(genre, genres[11]);
	else if (!strncasecmp(genre, "rel", 3))
		strcpy(genre, genres[13]);
	else if (strcasestr(genre, "serie"))
		strcpy(genre, genres[25]);
	else if (!strncasecmp(genre, "rom", 3))
		strcpy(genre, genres[26]);
	else if (!strncasecmp(genre, "sho", 3))
		strcpy(genre, genres[0]);
	else if (!strncasecmp(genre, "wet", 3))
		strcpy(genre, genres[15]);
	else if (!strncasecmp(genre, "nat", 3))
		strcpy(genre, genres[15]);
	else if (!strncasecmp(genre, "tec", 3))
		strcpy(genre, genres[15]);
	else if (!strncasecmp(genre, "spo", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "jeu", 3))
		strcpy(genre, genres[8]);
	else if (!strncasecmp(genre, "ki", 2))
		strcpy(genre, genres[8]);
	else if (!strncasecmp(genre, "det", 3))
		strcpy(genre, genres[12]);
	else if (!strncasecmp(genre, "act", 3))
		strcpy(genre, genres[12]);
	else if (!strncasecmp(genre, "tek", 3))
		strcpy(genre, genres[8]);
	else if (!strncasecmp(genre, "mus", 3))
		strcpy(genre, genres[7]);
	else if (!strncasecmp(genre, "muz", 3))
		strcpy(genre, genres[7]);
	else if (!strncasecmp(genre, "vri", 3))
		strcpy(genre, genres[12]);
	else if (strcasestr(genre, "film"))
		strcpy(genre, genres[6]);
	else if (!strncasecmp(genre, "thr", 3))
		strcpy(genre, genres[6]);
	else if (!strncasecmp(genre, "mov", 3))
		strcpy(genre, genres[6]);
	else if (!strncasecmp(genre, "wat", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "voe", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "mot", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "atl", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "tea", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "win", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "ten", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "ext", 3))
		strcpy(genre, genres[14]);
	else if (!strncasecmp(genre, "mel", 3))
		strcpy(genre, genres[12]);
	else if (!strncasecmp(genre, "bee", 3))
		strcpy(genre, genres[9]);
	else if (!strncasecmp(genre, "the", 3))
		strcpy(genre, genres[9]);
	else if (!strncasecmp(genre, "ero", 3))
		strcpy(genre, genres[5]);
	else if (!strncasecmp(genre, "tal", 3))
		strcpy(genre, genres[0]);
	else {
		//fprintf(stderr,"!! Onbekend genre %s\n", genre);
		strcpy(genre, "Overige");
	}
	return (1);

}

/* Bij niet-films, splits de title op in
 * titel en subtitel als er een ':' in
 * de titel zit
 */
void splits_titel(char* titel, char* subtitel, char* genre) 
{
      static int preg_init = 0;
      static regex_t preg;
      static regmatch_t* pmatch = NULL;

      // Initialiseer statics als nodig
      if (!preg_init) {
	regcomp(&preg, "[-[:space:]]+(afl|aflevering)[:.[:space:]]+", REG_EXTENDED|REG_ICASE);
        pmatch = (regmatch_t *)malloc( 5 * sizeof(regmatch_t) );
	preg_init = 1;
      }

      // Sla over als er al een subtitel is gevonden.
      // Splits ook filmtitels niet
      if (subtitel[0] != '\0' ||
	  !strcasecmp(genre,"film") ||
	  !strcasecmp(genre,"movies") ) {
	return;
      }

      // Zoek fragmenten als "afl:", "Afl.:", "afl.", "aflevering"
      if (regexec(&preg, titel, 5, pmatch, 0) == 0 ) {
	if (pmatch[0].rm_so>0) {
	  titel[pmatch[0].rm_so]='\0';
	  strncpy(subtitel, "Aflevering: ", 150);
	  strncat(subtitel, titel+pmatch[0].rm_eo, (size_t) 150-11);
	  return;
	}
      }

      // Splits anders op ": "
      // TODO: het zou beter zijn om op de /laatste/ : te splitsen
      char* dubbelepunt;
      if (dubbelepunt = strstr(titel,": ")) {
	strncpy(subtitel,dubbelepunt+2,150);
	*dubbelepunt = '\0';
      }
}

//Maken array van presentatoren/actors/regisseurs
short maak_presenters(char *data, char **pr)
{
	int tel = 0, tel2 = 0;
	int len;
	char *p2[50], *p3;
	char *temp;

	//fprintf(stderr, "presenter: '%s'\n", data);
	if (!data || data[0] == '\0') {
		pr[tel] = NULL;
		return (0);
	}
	// kopietje maken, om data niet te verminken.
	temp = malloc(sizeof(char) * (strlen(data) + 2));
	strcpy(temp, data);

	// strippen \r \n
	len = strlen(temp);
	while (temp[len - 1] == '\r' || temp[len - 1] == '\n') {
		temp[len - 1] = '\0';
		len = strlen(temp);
	}

	if ((p3 = strstr(temp, " e.a")))
		*p3 = '\0';
	//p2 = strtok_r(temp, "/,", &p3);
	//while(p2) {
	p2[tel2] = strtok_r(temp, "/,", &p3);
	tel2++;
	while (p2[tel2] = strtok_r(NULL, "/,", &p3)){
		tel2++;
		if(tel2 == 49)
			break;
	}
	for (tel2 = 0; p2[tel2]; tel2++) {
		while (isspace(*p2[tel2]) && *p2[tel2])
			p2[tel2] += 1;
		len = strlen(p2[tel2]);
		if (len) {
			p3 = strchr(p2[tel2], '.');
			while (p3) {
				if(len - strlen(p3) < 2)
					break;
				if (strncasecmp(&p3[-2], "dr.", 3)) {
					if (strlen(p3) <= 2) {
						*p3 = '\0';
						break;
					}
				}
				p3++;
				p3 = strchr(p3, '.');
			}
			if ((p3 = strstr(p2[tel2], " en "))) {
				*p3 = '\0';
				p3++;
				pr[tel] = strdup(p2[tel2]);
				p2[tel2] = p3 + 3;
				tel++;
				pr[tel] = strdup(p2[tel2]);
				tel++;
				continue;
			}
			pr[tel] = strdup(p2[tel2]);
			tel++;
		}
		//p2=strtok_r(NULL, "/,", &p3);
	}
	pr[tel] = NULL;
	for (tel = 0; pr[tel]; tel++) {
		if (p3 = strstr(pr[tel], " en"))
			*p3 = '\0';
		if (!strncmp(pr[tel], "of ", 3)) {
			strcpy(temp, pr[tel]);
			p3 = strchr(temp, ' ');
			p3++;
			strcpy(pr[tel], p3);
		}
		if (p3 = strstr(pr[tel], " ("))
			*p3 = '\0';
	}

	free(temp);
	return (1);

}
